package br.com.felix.fwt.ui;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import br.com.felix.fwt.log.LoggerFactory;
import br.com.felix.fwt.servlet.FelixWebToolkitServlet;
import br.com.felix.fwt.servlet.FwtContext;
import br.com.felix.fwt.ui.exception.ComponentRenderException;

/**
 * The Class ServerSideInclude allows us to include static or dynamic resources in the output.
 * It uses the RequestDispatcher.
 */
public class ServerSideInclude extends BaseComponent {

	private static final long serialVersionUID = -2352896772199135746L;
	
	private static Logger logger = LoggerFactory.getLogger(ServerSideInclude.class);

	/**
	 * Instantiates a new server side include.
	 * 
	 * @param path the path
	 */
	public ServerSideInclude(String path){
		setValue(path);
	}
	
	/* (non-Javadoc)
	 * @see br.com.felix.fwt.ui.BaseComponent#write(java.io.PrintWriter)
	 */
	@Override
	public void write(PrintWriter out) throws ComponentRenderException {
		if(!authorized()) return;
		FwtContext ctx = FelixWebToolkitServlet.getFwtContext();
		HttpServletRequest request = ctx.request;
		RequestDispatcher dispatcher = request.getRequestDispatcher("/" + getValue());

		try {
			dispatcher.include(request, ctx.response);
		} 
		catch (ServletException e) {
			String msg = "Could not include file '"+getValue()+"' in the HttpResponse. A ServletException ocurred.";
			logger.error(msg, e);
            throw new ComponentRenderException(msg, e);
		} 
		catch (IOException e) {
		    String msg = "Could not include file '"+getValue()+"' in the HttpResponse. An IOException ocurred.";
            logger.error(msg, e);
            throw new ComponentRenderException(msg, e);
        }
	}

}
